//
//  YCNetworkManager.swift
//  WeiboDemo
//
//  Created by 尹成 on 2017/1/11.
//  Copyright © 2017年 yc. All rights reserved.
//

import UIKit
import AFNetworking


/// Swift 枚举支持任意数据类型
enum YCHTTPMethod {
    case GET
    case POST
}

/// 网络管理工具
class YCNetworkManager: AFHTTPSessionManager {
    
    /// 单例
    static let shared:YCNetworkManager = {
        let instance = YCNetworkManager()
        
        /// 设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
//    var accessToken: String?// = UserDefaults.object("AccessToken")
//    var uid:String?
    lazy var userAccount = YCUserAccount()
    
    /// 计算性属性
    var userLogon:Bool{
        return userAccount.access_token != nil
    }
    
    private func needLogin(tokenError:Bool=false) -> () {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: YCUserShouldLoginNotification), object: (tokenError == false ? nil : "Token Error"))
    }
    
    /// 拼接token
    func tokenRequest(parameters:[String:AnyObject]?) -> ([String:AnyObject]?) {
        
        /** 1.判断token 是否存在,存在则设置token
            2.否则判断是否是登录接口,是则放过,否则调用登录模块
            3.若token过期,则需要重新登录
         */
        
        // FIXME: 此处需要修正，无token时登录请求，无token时数据请求
        
        guard let token = userAccount.access_token else {
            //无token,需要登录
            needLogin()
            return nil
        }
        
        var parameters = parameters
        if parameters == nil {
            //实例化字典
            parameters = [String:AnyObject]()
        }
        parameters!["access_token"] = token as AnyObject?
        
        return parameters
    }
    
    ///使用一个函数封装 get / post
    func request(method:YCHTTPMethod = .GET,
                 URLString:String,
                 parameters:[String:AnyObject]?,
                 needToken:Bool=true,
                 completion:@escaping (_ result:Any?, _ isSuccess:Bool) -> ()){
        
        var parameters = parameters
        if needToken {
            guard let tempparameters = tokenRequest(parameters: parameters) else {
                return
            }
            parameters = tempparameters
        }
        
        let success = { (task:URLSessionDataTask,result:Any?) -> () in
            completion(result,true)
        }
        
        let failure = { (task:URLSessionDataTask?,error:Error) -> () in
            
            //针对403(拒绝访问,token过期)处理
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token 过期")
                //需要登录
                self.needLogin(tokenError: true)
                return
            }
            
            completion(nil,false)
            print("error:",error)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
}
